package web;

import com.example.book.pojo.User;
import com.example.book.service.Impl.UserServiceImpl;
import com.example.book.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yanhuanzhan
 * @date 2021/12/27 - 1:42
 */
public class UserServlet extends BaseServlet{
    UserService userService = new UserServiceImpl();
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1,获取请求参数
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        //2,调用service处理业务
        if (userService.login(new User(null, userName, password, null)) != null) {
            System.out.println("登陆成功");
            req.getRequestDispatcher("pages/user/login_success.jsp").forward(req,resp);
        }else {
            System.out.println("登陆失败");
            //把错误信息和回显的表单项信息保存到request域中
            req.setAttribute("msg","用户名或密码错误!");
            req.setAttribute("username",userName);
            req.setAttribute("password",password);
            //跳回登录界面
            req.getRequestDispatcher("pages/user/login.jsp").forward(req,resp);
        }
    }
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1,获取请求参数
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        //2,检查验证码是否正确 ---写死，验证码为abcde
        if ("abcde".equalsIgnoreCase(code)) {//忽略大小写
            //检查用户名是否可用
            if (userService.existsUsername(userName)) {
                //不可用
                System.out.println("用户名"+userName+"不可用");
                //把错误信息和回显示信息保存到request域中
                req.setAttribute("msg","用户名已存在!");
                req.setAttribute("username",userName);
                req.setAttribute("email",email);
                req.getRequestDispatcher("pages/user/regist.jsp").forward(req,resp);
            } else {
                //用户名可用
                userService.registUser(new User(null,userName,password,email));
                req.getRequestDispatcher("pages/user/regist_success.jsp").forward(req,resp);
            }
        }else {
            //把错误信息和回显示信息保存到request域中
            req.setAttribute("msg","验证码错误!");
            req.setAttribute("username",userName);
            req.setAttribute("email",email);
            //跳回注册页面
            req.getRequestDispatcher("pages/user/regist.jsp").forward(req,resp);
        }
    }
}
